package com.xu.ai.mcp.syncclient.controller;

import java.util.Map;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import com.alibaba.cloud.ai.dashscope.spec.DashScopeModel;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * ChatClient聊天客户端 controller
 *
 * @author xuguan
 * @since 2025/11/3
 */
@RestController
@RequestMapping("/api/mcp/sync-client/chat")
public class ChatController {
	private final ChatClient chatClient;
	private final ToolCallbackProvider toolCallbackProvider;

	public ChatController(ChatClient.Builder chatClientBuilder,
						  ToolCallbackProvider toolCallbackProvider) {
		this.toolCallbackProvider = toolCallbackProvider;
		this.chatClient = chatClientBuilder
				.defaultOptions(DashScopeChatOptions.builder()
						.model(DashScopeModel.ChatModel.QWEN_PLUS.getName())
						.build())
				.defaultToolCallbacks(toolCallbackProvider)
				.defaultAdvisors(SimpleLoggerAdvisor.builder().build())
				.build();
	}

	@GetMapping("/calculate")
	public Flux<String> calculate(@RequestParam("a") int a,
								  @RequestParam("b") int b) {
		final PromptTemplate prompt = PromptTemplate.builder()
				.template("""
						计算两个数之和: {a} + {b} = ?,
												
						例如: 1 + 1 = 2,
												
						输出结果:
						""")
				.variables(Map.of("a", a, "b", b))
				.build();
		return chatClient.prompt(prompt.getTemplate()).stream().content();
	}
}
